var page = require('webpage').create();
console.log("###start login...");
page.open("http://www.chunyuyisheng.com/ask/clinic/problems/new", function(status) {
    if (status == "success") {
        page.evaluate(function() {
            document.getElementById("id_username").value = "15926329127";
            document.getElementById("id_password").value = "19878689948";
            document.getElementById("loginBtn").click();
        });
        console.log("###login success");
        setTimeout(function() {
            console.log("###start searching...");
            setInterval(function() {
                page.open("http://www.chunyuyisheng.com/ask/clinic/problems/new", function(status) {
                    //page.render('login_in.png');
                    var txtUrl = page.evaluate(function() {
                        var obj = document.getElementById("problemsList");
                        if (obj) {
                            var url = obj.children[0].children[1].children[0].children[0].children[0].href;
                            return url;
                        }
                    });
                    var myDate = new Date();
                    var time = myDate.getHours() + ":" + fomart(myDate.getMinutes()) + ":" + fomart(myDate.getSeconds());
                    var time_file = myDate.getHours() + "-" + fomart(myDate.getMinutes()) + "-" + fomart(myDate.getSeconds());
                    if (txtUrl) {
                        console.log(time + " " + txtUrl);
                        var page_dtl = require('webpage').create();
                        page_dtl.open(txtUrl, function(status) {
                            var assignurl = page_dtl.evaluate(function() {
                                return $("a[class='btn btn-primary']").attr("href");
                            });
                            console.log("assignurl:" + assignurl);
                            if (assignurl) {
                                var page_assign = require('webpage').create();
                                page_assign.open("http://www.chunyuyisheng.com" + assignurl, function(status) {
                                    //page_assign.render(time_file + 'assgn.png');
                                    console.log("get ok");
                                });
                                return mybtn[0].outerHTML + "|" + $("a[class='btn btn-primary']").length;
                            }
                            else {
                                return "geted by other people";
                            }
                        });
                    }
                    else {
                        console.log(time + " no question");
                    }
                });
            }, 10000);
        }, 2000);
    }
    else {
        console.log("error1:" + status);
    }
});

function fomart(i) {
    return i < 10 ? "0" + i.toString() : i.toString();
}